package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 131. 分割回文串
 * @date 2025/5/25 12:02
 */
public class E131 {

    /**
     * 回溯+记忆数组
     *
     * @param s 字符串
     * @return 所有分割结果
     */
    public List<List<String>> partition(String s) {
        char[] charArray = s.toCharArray();
        int n = charArray.length;
        boolean[][] memory = new boolean[n][n];
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                memory[i][j] = isPalindrome(charArray, i, j);
        List<List<String>> result = new ArrayList<>();
        dfs(charArray, result, new LinkedList<>(), 0, memory);
        return result;
    }

    /**
     * 回溯
     *
     * @param charArray 字符数组
     * @param result    结果
     * @param curr      当前结果
     * @param start     开始位置
     * @param memory    记忆数组
     */
    private void dfs(char[] charArray, List<List<String>> result,
                     Deque<String> curr, int start, boolean[][] memory) {
        if (start == charArray.length) {
            result.add(new ArrayList<>(curr));
            return;
        }
        for (int i = start; i < charArray.length; i++) {
            if (memory[start][i]) {
                curr.offerLast(new String(charArray, start, i - start + 1));
                dfs(charArray, result, curr, i + 1, memory);
                curr.pollLast();
            }
        }
    }

    /**
     * 判断是否是回文
     *
     * @param charArray 字符数组
     * @param begin     开始位置
     * @param end       结束位置
     * @return 是否是回文
     */
    private boolean isPalindrome(char[] charArray, int begin, int end) {
        while (begin <= end) {
            if (charArray[begin] == charArray[end]) {
                begin++;
                end--;
            } else {
                return false;
            }
        }
        return true;
    }
}
